const util = require('../../utils/util');
const request = require('../../utils/request');
const locationMap = require('../../utils/map');
const map = require('../../utils/map');

Page({

    /**
     * 页面的初始数据
     */
    data: {
        //自定义头部
        navbarHeight: 0,

        //选项卡
        tabActiveIndex: 0,

        //头部滚动
        scrollTop: 0,


        //这个是头部banner轮播
        currentSwiper: 0,

        // 这个是今日必拼轮播
        currentSwiperView: 0,

        // 编辑开关
        // addSwitch: false,

        // 计算 input默认是1  
        num: 1,

        //这个是导航栏轮播
        currentSwiperNav: 0,

        bannerList: [],

        goods_classbottom: [], //下面的分类
        goods_class: [], //分类

        goods_list: [], //所有商品列表
        goods_classlist_other: [], //其他分类列表
        goods_classlist_hot: [], //热销好货
        goodsLinJu: [], //邻居们都在买
        store: '', //当前选择点

        page: 1,
        isLastPage: false,
        cate_id: '', //分类id

        pintuan: null, //拼团列表
        location: {},

        // 最近小区
        localXiaoqu: {}
    },

    /**
     * 生命周期函数--监听页面加载
     */

    onLoad: function (options) {
        let _this = this
        this.setData({
            navbarHeight: util.getNavbarHeight(),
        })
        //改变头部电量条背景色
        wx.setNavigationBarColor({
            frontColor: '#ffffff',
            backgroundColor: '#ffffff',
        })
        const scene = decodeURIComponent(options.scene)
        if (scene && scene != 'undefined' && scene != null) {
            // 跳转商品详情
            wx.navigateTo({
                url: '/pages/home/pages/my/product-details',
                success: function (res) {}
            })
            return
        }

        if (wx.getStorageSync('token')) {
            getApp().getCartNum()
        }

        this.setData({
            isLastPage: false,
            goods_list: [],
            page: 1,
            tabActiveIndex: 0
        })
        this.getList()
    },
    // 首次获取地理位置获取最近的小区
    getCurrentXiaoqu(coordinate) {
        let _this = this
        request._post('/api?method=merchants.firstXiaoqu', {
            coordinate
        }, 'noload').then(res => {
            _this.setData({
                localXiaoqu: res.data[0]
            })
            wx.setStorage({
                key: 'localXiaoqu',
                data: res.data[0],
            })
            _this.getList()

        })
    },
    shuaxin(){
      // 获取购物车列表
      request._post('/api?method=cart.cartlist', {
        xiaoqu: wx.getStorageSync('localXiaoqu') ? wx.getStorageSync('localXiaoqu').id : ''
      }).then(res => {
          let cartList = res.data.ori_goods_list
          if(cartList){
            let list = this.data.goods_list
            list.forEach((item)=>{
              item.cart_num = 0
              item.addSwitch = false
              cartList.forEach((cart)=>{
                if(item.goods_id == cart.goods_id){
                  item.cart_num = cart.nums
                  item.addSwitch = true
                }
              })
            })
            let goods = this.data.goodsLinJu
            goods.forEach((item)=>{
              item.cart_num = 0
              item.addSwitch = false
              cartList.forEach((cart)=>{
                if(item.goods_id == cart.goods_id){
                  item.cart_num = cart.nums
                  item.addSwitch = true
                }
              })
            })
            this.setData({
              goodsLinJu: goods,
              goods_list: list
            })
          }

      })
    },
    onShow() {
        if (getApp().globalData.isFirstLogin) {
            this.setData({
              isLastPage: false,
              goods_list: [],
              page: 1,
              tabActiveIndex: 0
            })
            this.getList()
            getApp().globalData.isFirstLogin = false
        }
        if (wx.getStorageSync('token')) {
            getApp().getCartNum()
        }
        let cartList = wx.getStorageSync('cartList')
        if(cartList){
          let list = this.data.goods_list
          list.forEach((item)=>{
            item.cart_num = 0
            item.addSwitch = false
            cartList.forEach((cart)=>{
              if(item.goods_id == cart.goods_id){
                item.cart_num = cart.nums
                item.addSwitch = true
              }
            })
          })
          // let goods = this.data.goodsLinJu
          // goods.forEach((item)=>{
          //   item.cart_num = 0
          //   item.addSwitch = false
          //   cartList.forEach((cart)=>{
          //     if(item.goods_id == cart.goods_id){
          //       item.cart_num = cart.nums
          //       item.addSwitch = true
          //     }
          //   })
          // })
          this.setData({
            // goodsLinJu: goods,
            goods_list: list
          })
        }
    },
    /**
     * 选项卡
     */
    tabClick(e) {
        const index = e.currentTarget.dataset.index;
        const item = e.currentTarget.dataset.item
        this.setData({
            goods_list: [],
            page: 1,

        })
        this.setData({
            isLastPage: false,
            cate_id: item.id
        })
        this.getGoods_list()
        this.setData({
            tabActiveIndex: index
        })
    },

    /**
     * 头部滚动
     */
    onPageScroll(e) {
        this.setData({
            scrollTop: e.scrollTop,
        });
    },

    /**
     * 这个是头部banner轮播
     * swiper内容左右滑动切换触发
     */
    swiperChange(e) {
        const current = e.detail.current;
        this.setData({
            currentSwiper: current, // 更新当前选中
        });
    },

    /**
     * 这个是导航栏轮播
     * swiper内容左右滑动切换触发
     */
    swiperChangeView(e) {
        const currentView = e.detail.current;
        this.setData({
            currentSwiperView: currentView, // 更新当前选中
        });
    },
    showClassNav(){
      this.setData({
        showCate: !this.data.showCate, // 更新当前选中
      });
    },
    // 轮播分类跳列表
    bannerTo(e) {
        let item = e.currentTarget.dataset.item
        getApp().globalData.cate_id = item.id
        wx.switchTab({
            url: "/pages/classification/classification"
        })
        // wx.navigateTo({
        //     url: '/pages/home/pages/my/product-list/index?id=' + item.id,
        // })
    },
    // 邻居们都在买查看更多
    lookMore() {
        wx.navigateTo({
            url: '/pages/home/pages/my/product-list/index',
        })
    },
    /**
     * 这个是今日必拼轮播
     * swiper内容左右滑动切换触发
     */
    swiperChangeNav(e) {
        const currentNav = e.detail.current;
        this.setData({
            currentSwiperNav: currentNav, // 更新当前选中
        });
    },

    /**
     * 加入购物车
     */

    add(e) {
      let item = e.detail.item ? e.detail.item : e.currentTarget.dataset.item
      let index = e.detail.index ? e.detail.index : e.currentTarget.dataset.index || 0
      let listType = e.detail.ntype ? e.detail.ntype : e.currentTarget.dataset.ntype
        let goodsLinJu = listType == 'linju' ? this.data.goodsLinJu : this.data.goods_list
        if (!item.addSwitch) {
            item.addSwitch = true
            item.cart_num++
        }
        this.addCartApi(item, index, listType)
        if(goodsLinJu[index].product_id == item.id){
          goodsLinJu[index].cart_num = item.cart_num
          goodsLinJu[index].addSwitch = item.addSwitch
        }
        if(listType == 'linju'){
          this.setData({
            goodsLinJu
          })
        }else{
          this.setData({
            goods_list: goodsLinJu
          })
        }
    },
    // 购物车加减
    addCartReduce(e) {
        let type = e.detail.type ? e.detail.type : e.currentTarget.dataset.type //1 减 2 加
        let item = e.detail.item ? e.detail.item : e.currentTarget.dataset.item
        let index = e.detail.index ? e.detail.index : e.currentTarget.dataset.index || 0
        let listType = e.detail.ntype ? e.detail.ntype : e.currentTarget.dataset.ntype
        let goodsLinJu = listType == 'linju' ? this.data.goodsLinJu : this.data.goods_list
        if (type == 1) {
          if(item.cart_num == 0) return
            item.cart_num--
        } else {
            item.cart_num++
        }

        this.addCartApi(item, index, listType)
        goodsLinJu[index] = Object.assign(goodsLinJu[index], item)
        if(listType == 'linju'){
          this.setData({
            goodsLinJu
          })
        }else{
          this.setData({
            goods_list: goodsLinJu
          })
        }
    },
    addCartApi(item, index, listType) {
      let goodsLinJu = listType == 'linju' ? this.data.goodsLinJu : this.data.goods_list
      request._post('/api?method=cart.add', {
          product_id: item.product_id || item.id,
          nums: item.cart_num,
          num_type: 2,
      }, 'noload').then(res => {
        console.log('数量==》'+item.cart_num,listType)
        if (item.cart_num == 0) {
          goodsLinJu[index].addSwitch = false
          if(listType == 'linju'){
            this.setData({
              [`goodsLinJu[${index}]`]: goodsLinJu[index]
            })
          }else{
            this.setData({
              [`goods_list[${index}]`]: goodsLinJu[index]
            })
          }
        }
        getApp().getCartNum()
      }).catch(res => {
          // 库存不足情况--
          let goodsLinJu = listType == 'linju' ? this.data.goodsLinJu : this.data.goods_list
          goodsLinJu[index].cart_num--
          if (goodsLinJu[index].cart_num <= 0) {
              goodsLinJu[index].addSwitch = false
          }
          if(listType == 'linju'){
            this.setData({
              [`goodsLinJu[${index}]`]: goodsLinJu[index]
            })
          }else{
            this.setData({
              [`goods_list[${index}]`]: goodsLinJu[index]
            })
          }
      })
    },

    /**
     * 输入框事件
     */
    bindManual: function (e) {
        var num = e.detail.value;
        this.setData({
            num: num
        });
    },

    /**
     *搜索 
     */
    search() {
        wx.navigateTo({
            url: '/pages/home/pages/my/search/search',
        })
    },
    /**
     *拼团详情 
     */
    group(e) {
        let item = e.currentTarget.dataset.item
        wx.navigateTo({
            url: '/pages/home/pages/my/group-details/group-details?id=' + item.order_id,
        })
    },
    /**
     *商品详情 
     */
    toDetail(e) {
        let item = e.currentTarget.dataset.item
        let type = e.currentTarget.dataset.type
        let id = type == 2 ? item.id : item.goods_id
        wx.navigateTo({
            url: '/pages/home/pages/my/product-details/product-details?id=' + id,
        })
    },
    // 处理中间分类
    dealClass(datas) {
        var chunk = 10; //10 份等分
        var len = datas.length;
        var result = [];
        if(len > 5){
          result = datas.slice(0, 5)
        }
        // for (let i = 0; i < len; i += chunk) {
        //     result.push(datas.slice(i, i + chunk)) // 每10项分成一组        
        // }
        return result
    },
    dealClassBtm() {
        let goods_classbottom = this.data.goods_classbottom
        // let obj = {
        //     id: 0,
        //     name: '热销好货',
        // }
        // goods_classbottom.unshift(obj)
        this.setData({
            goods_classbottom
        })
    },
    //获取当前地理位置
    getLocation() {
        let _this = this
        locationMap.getLocation(this, function (res) {
            let o = res.result
            if (res.status == 0) {

                let info = {
                    lat: o.location.lat,
                    lng: o.location.lng,
                    address: o.address,
                    city: o.address_component.city
                }
                let coordinate = String(o.location.lat) + ',' + String(o.location.lng)
                _this.getCurrentXiaoqu(coordinate)
            }
        })
    },
    // 获取首页信息
    getList(lat, lng) {
        let _this = this
        request._post('/api?method=merchants.merchants', {
            xiaoqu: wx.getStorageSync('localXiaoqu').id
        }).then(res => {
            res.data.goods.forEach(function (obj, index) {
                obj.addSwitch = false
                if (obj.cart_num) {
                    obj.addSwitch = true
                }
            })
            _this.setData({
                bannerList: res.data.banner,
                goods_class: _this.dealClass(res.data.goods_class),
                categoryList:res.data.goods_class,
                goods_classbottom: res.data.goods_class,
                store: res.data.store,
                goodsLinJu: res.data.goods,
                goods_classlist_hot: res.data.goods_hot,
                isLastPage: true,
                pintuan: res.data.pintuan,
                // cate_id: res.data.goods_class[0].id
            })

            // 存储地理位置信息
            // let store = res.data.store
            // store.isFirstGet = true
            _this.getGoods_list()
        })
    },
    // 根据分类传调用商品列表
    getGoods_list() {
        let _this = this
        let isLastPage = this.data.isLastPage
        request._post('/api?method=merchants.goodsList', {
            page: this.data.page,
            cate_id: this.data.cate_id,
            store: 0,
            xiaoqu: wx.getStorageSync('localXiaoqu').id
        },'noload').then(res => {
            if (res.data && res.data.length == 0) {
                isLastPage = true
            } else {
                isLastPage = false
            }
            res.data.forEach(function (obj, index) {
              obj.addSwitch = false
              if (obj.cart_num) {
                  obj.addSwitch = true
              }
            })
            _this.setData({
                goods_list: _this.data.goods_list.concat(res.data),
                isLastPage
            })
        })
    },
    // 选择当前点
    chooseLocation() {
        wx.navigateTo({
            url: '/pages/home/pages/my/peisongdian/peisongdian',
        })
    },
    // 上拉加载
    onReachBottom: function () {
        let page = this.data.page
        if (this.data.isLastPage) {
            return
        }
        page++
        this.setData({
            page
        })
        this.getGoods_list()
    },
    onShareAppMessage: function () {
        // let info = this.data.detailinfo
        return {
            title: '品质生活 至美到家（次日达）',
            path: '/pages/index/index', //旅居详情
            imageUrl: this.data.bannerList[0].img
        }
    },
    onPullDownRefresh: function () {
        let _this = this
        wx.showToast({
            title:'刷新中...',
            icon:'none',
            duration:1000
        })
        // 更新数据的逻辑
        this.setData({
            isLastPage: false,
            goods_list: [],
            page: 1,
            tabActiveIndex: 0
        })
        setTimeout(function(){
            wx.hideLoading()
            _this.getList()
            // _this.getLocation()
        },500)
        
       
        wx.stopPullDownRefresh();

    }

})